﻿using Spine.Unity;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace Learning.Spine
{
    /// <summary>
    /// UI 上展示的边缘虚化的 Spine 加载和使用工具类
    /// 注意：实现上是通过一个额外的摄像机对场景里的Spine拍照后在RawImage上进行展示
    /// </summary>
    public static class EdgeSpineUtil
    {
        private static GameObject _root;
        private static Camera _camera;
        private static RenderTexture _renderTexture;
        
        public static void Init()
        {
            _root = new GameObject("EdgeSpine");
            
            var asset = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Spine/Runtime/Script/SpineCamera.prefab");
            var go = GameObject.Instantiate(asset);
            go.transform.SetParent(_root.transform, false);
            _camera = go.GetComponent<Camera>();
            
            _renderTexture = RenderTexture.GetTemporary(1024, 1024);
            _camera.targetTexture = _renderTexture;
        }
        
        public static void LoadSpine(string spinePath, RawImage rawImage, string animName)
        {
            rawImage.texture = _renderTexture;
            
            var asset = AssetDatabase.LoadAssetAtPath<GameObject>(spinePath);
            var go = GameObject.Instantiate(asset);
            
            go.transform.SetParent(_root.transform, false);
            go.transform.localPosition = new Vector3(0, -2, 0);
            
            var skeletonGraphic = go.GetComponent<SkeletonAnimation>();
            skeletonGraphic.AnimationState.SetAnimation(0, animName, true);

            var mat = AssetDatabase.LoadAssetAtPath<Material>("Assets/Spine/Runtime/Material/UIAlphaGradient.mat");
            mat = Material.Instantiate(mat);
            
            mat.SetVector("_GradientValue", new Vector4(0.17f, 0.07f, 0.28f, 0.28f));
            mat.SetFloat("_GradientSmooth", 0.12f);
            mat.SetVector("_GradientValue2", new Vector4(0.1f, 0.1f, 0.1f, 0.1f));
            mat.SetFloat("_GradientSmooth2", 0.08f);
            
            rawImage.material = mat;
        }

        public static void Clear()
        {
            GameObject.Destroy(_root);
            RenderTexture.ReleaseTemporary(_renderTexture);
            _root = null;
            _camera = null;
            _renderTexture = null;
        }
    }
}
